package logic

import (
	"context"
	"encoding/json"
	"strconv"

	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

type ServeyClassifyDetailLogic struct {
	logx.Logger
	ctx    context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	modelSC model.ServeyClassifyModel
}

var ServeyClassifyDetailPrefix string = "servey:classify:id:"

func NewServeyClassifyDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServeyClassifyDetailLogic {
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &ServeyClassifyDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		rds: rds,
		svcCtx: svcCtx,
		modelSC: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
	}
}

func (l *ServeyClassifyDetailLogic) ServeyClassifyDetail(req *types.IdRequest) (resp *types.ServeyClassifyDetailResponse, err error) {
	// todo: add your logic here and delete this line
	// 检查缓存中是否存在该条数据，如果存在则返回缓存中的数据，如果不存在则从数据库中获取并保存于缓存中
	data, err := l.rds.GetCtx(l.ctx, ServeyClassifyDetailPrefix+strconv.FormatInt(req.Id, 10))
	if len(data) > 0 {
		var serveyClassifyInfo *types.ServeyClassifyInfoItemResponse
		err = json.Unmarshal([]byte(data), &serveyClassifyInfo)
		if err != nil {
			return nil, err
		}
		l.rds.ExpireCtx(l.ctx, ServeyClassifyDetailPrefix+strconv.FormatInt(req.Id, 10), 3600*2)
		return &types.ServeyClassifyDetailResponse{
			Code: 200,
			Msg:  "search success",
			Data: *serveyClassifyInfo,
		}, nil
	}
	serveyClassify,err := l.modelSC.FindOne(l.ctx,req.Id)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}

	serveyClassifyResp := &types.ServeyClassifyInfoItemResponse{
		Id: serveyClassify.Id,
		ClfName: serveyClassify.ClfName,
		ClfDesc: serveyClassify.ClfDesc.String,
		ServeyNum: serveyClassify.ServeyNum,
	}

	byteData,err := json.Marshal(serveyClassify)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	_,err = l.rds.SetnxExCtx(l.ctx,ServeyClassifyDetailPrefix + strconv.FormatInt(req.Id,10),string(byteData),3600 * 2)

	return &types.ServeyClassifyDetailResponse{
		Code: 200,
		Msg: "search detail success",
		Data: *serveyClassifyResp,
	},nil
}
